<template>

	<a-alert message="请先验证手机号" type="error" :closable="false" v-if="!formData.phoneVerified"/>
	<a-alert message="请先验证邮箱" type="warning" :closable="false" v-if="!formData.emailVerified" style="margin:10px 0"/>

	<a-form
		ref="formRef"
		:model="formData"
		:rules="formRules"
		v-bind="layout"
		:label-col="{ ...layout.labelCol, offset: 0 }"
		:wrapper-col="{ ...layout.wrapperCol, offset: 0 }"
	>
		<a-form-item label="账号：" name="account">
			<span>{{ formData.account }}</span>
		</a-form-item>
		<a-form-item label="姓名：" name="name">
			<a-input v-model:value.trim="formData.name" placeholder="请输入姓名" allow-clear/>
		</a-form-item>
		<a-form-item label="手机：" name="phone">
			<div style="display: flex;align-items:center;">
				<a-input v-model:value.trim="formData.phone" placeholder="请输入手机" allow-clear>
				</a-input>
				<a-button style="margin-left:10px;" @click="showPhoneValidation" v-if="!formData.phoneVerified">立即验证
				</a-button>
				<CheckCircleOutlined style="color:#00ff80;font-size:25px;margin-left:10px;" v-else/>
			</div>
		</a-form-item>
		<a-form-item label="邮箱：" name="email" style="display: flex">
			<div style="display: flex;align-items:center;">
				<a-input v-model:value.trim="formData.email" placeholder="请输入邮箱" allow-clear>
				</a-input>
				<a-button style="margin-left:10px;" v-if="!formData.emailVerified" @click="showEmailValidation">立即验证
				</a-button>
				<CheckCircleOutlined style="color:#00ff80;font-size:25px;margin-left:10px;" v-else/>
			</div>
		</a-form-item>
		<a-form-item label="昵称：" name="nickname">
			<a-input v-model:value.trim="formData.nickname" placeholder="请输入昵称" allow-clear/>
		</a-form-item>
		<a-form-item label="性别：" name="sex">
			<a-radio-group v-model:value="formData.gender" :options="genderOptions"></a-radio-group>
		</a-form-item>
		<a-form-item label="生日：" name="birthday">
			<a-date-picker v-model:value="formData.birthday" value-format="YYYY-MM-DD" style="width: 100%"/>
		</a-form-item>
		<a-form-item :wrapper-col="{ ...layout.wrapperCol, offset: 4 }">
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存基本信息</a-button>
		</a-form-item>
	</a-form>


	<!--	手机号验证   -->
	<a-modal
		v-model:visible="phoneValidationVisible"
		title="手机号验证"
		:width="600"
		@cancel="cancelPhoneValidation"
		@ok="validatePhone">
		<a-form ref="phoneValidationFormRef" :model="phoneValidationFormData" :rules="phoneValidationFormRules">
			<a-form-item label="当前手机号：" name="phone">
				<a-input v-model:value.trim="phoneValidationFormData.phone" disabled/>
			</a-form-item>
			<a-form-item label="短信验证码：" name="validCode">
				<a-row :gutter="8">
					<a-col :span="18">
						<a-input v-model:value.trim="phoneValidationFormData.validCode"/>
					</a-col>
					<a-col :span="6">
						<a-button @click="showPhoneMachineVerification" :disabled="phoneState.smsSendBtn">
							{{ (!phoneState.smsSendBtn && '获取验证码') || phoneState.time + ' s' }}
						</a-button>
					</a-col>
				</a-row>
			</a-form-item>
		</a-form>
	</a-modal>

	<!--	手机号验证-机器验证弹框 -->
	<a-modal
		v-model:visible="phoneMachineValidationVisible"
		:width="400"
		title="手机号验证"
		@ok="sendPhoneVerifyCode"
	>
		<a-form ref="phoneMachineValidationRef" :model="phoneMachineValidationFormData"
				:rules="phoneMachineValidationFormRules">
			<a-form-item name="validCode">
				<a-row :gutter="8">
					<a-col :span="17">
						<a-input
							v-model:value="phoneMachineValidationFormData.validCode"
							:placeholder="$t('login.validLaceholder')"
							size="large"
						>
							<template #prefix>
								<verified-outlined style="color: rgba(0, 0, 0, 0.25)"/>
							</template>
						</a-input>
					</a-col>
					<a-col :span="7">
						<img
							:src="phoneMachineValidCodeBase64"
							style="border: 1px solid var(--border-color-split); cursor: pointer; width: 100%; height: 40px"
							@click="showPhoneMachineVerification"
						/>
					</a-col>
				</a-row>
			</a-form-item>
		</a-form>
	</a-modal>


	<!--	邮箱验证   -->
	<a-modal
		v-model:visible="emailValidationVisible"
		title="邮箱验证"
		:width="600"
		@cancel="cancelEmailValidation"
		@ok="validateEmail">
		<a-form ref="emailValidationFormRef" :model="emailValidationFormData" :rules="emailValidationFormRules">
			<a-form-item label="当前邮箱：" name="email">
				<a-input v-model:value.trim="emailValidationFormData.email" disabled/>
			</a-form-item>
			<a-form-item label="验证码：" name="validCode">
				<a-row :gutter="8">
					<a-col :span="18">
						<a-input v-model:value.trim="emailValidationFormData.validCode"/>
					</a-col>
					<a-col :span="6">
						<a-button @click="showEmailMachineVerification" :disabled="emailState.emailSendBtn">
							{{ (!emailState.emailSendBtn && '获取验证码') || emailState.time + ' s' }}
						</a-button>
					</a-col>
				</a-row>
			</a-form-item>
		</a-form>
	</a-modal>

	<!--	邮箱验证-机器验证弹框   -->
	<a-modal
		v-model:visible="emailMachineValidationVisible"
		:width="400"
		:title="$t('login.machineValidation')"
		@ok="sendEmailVerifyCode"
	>
		<a-form ref="emailMachineValidationRef" :model="emailMachineValidationFormData"
				:rules="emailMachineValidationFormRules">
			<a-form-item name="validCode">
				<a-row :gutter="8">
					<a-col :span="17">
						<a-input
							v-model:value="emailMachineValidationFormData.validCode"
							:placeholder="$t('login.validLaceholder')"
							size="large"
						>
							<template #prefix>
								<verified-outlined style="color: rgba(0, 0, 0, 0.25)"/>
							</template>
						</a-input>
					</a-col>
					<a-col :span="7">
						<img
							:src="emailMachineValidCodeBase64"
							style="border: 1px solid var(--border-color-split); cursor: pointer; width: 100%; height: 40px"
							@click="showEmailMachineVerification"
						/>
					</a-col>
				</a-row>
			</a-form-item>
		</a-form>
	</a-modal>

</template>

<script setup name="AccountBasic">
	import {message} from 'ant-design-vue'
	import {getCurrentInstance} from 'vue'
	import tool from '@/utils/tool'
	import {required, rules} from '@/utils/formRules'
	import userCenterApi from '@/api/sys/userCenterApi'
	import smsApi from '@/api/dev/smsApi'
	import loginApi from '@/api/auth/loginApi'

	/**
	 * 验证手机号弹窗
	 */
		// 1. 验证手机号-图片码弹窗
	const phoneMachineValidationVisible = ref(false)
	const phoneMachineValidationFormData = ref({})
	const phoneMachineValidCodeBase64 = ref('')
	const phoneMachineValidationRef = ref()
	const phoneMachineValidationFormRules = {
		validCode: [required('请输入图形验证码'), rules.lettersNum]
	}
	const phoneValidationVisible = ref(false)
	const phoneValidationFormRef = ref()
	const phoneValidationFormData = ref({})
	const phoneValidationFormRules = {
		phone: [required('请输入11位手机号'), rules.phone],
		validCode: [required('请输入短信验证码'), rules.number]
	}
	let phoneState = ref({
		time: 300,
		smsSendBtn: false,
	})
	/***
	 * 邮箱验证弹窗
	 */
		// 1. 验证邮箱-图片码弹窗
	const emailMachineValidationVisible = ref(false)
	const emailMachineValidationFormData = ref({})
	const emailMachineValidCodeBase64 = ref('')
	const emailMachineValidationRef = ref()
	const emailMachineValidationFormRules = {
		validCode: [required('请输入图形验证码'), rules.lettersNum]
	}
	const emailValidationVisible = ref(false)
	const emailValidationFormRef = ref()
	const emailValidationFormData = ref({})
	const emailValidationFormRules = {
		email: [required('请输入正确的邮箱'), rules.email],
		validCode: [required('请输入邮箱验证码'), rules.number]
	}
	let emailState = ref({
		time: 300,
		emailSendBtn: false,
	})

	const formRef = ref()
	const {proxy} = getCurrentInstance()
	// 获取用户信息
	const userInfo = proxy.$TOOL.data.get('USER_INFO')
	let formData = ref({})
	formData.value = userInfo
	const submitLoading = ref(false)
	// 默认要校验的
	const formRules = {
		name: [required('请输入姓名')],
		gender: [required('请选择性别')],
		phone: [required('请输入11位手机号'), rules.phone],
		email: [required('请输入正确的邮箱地址'), rules.email]
	}
	const genderOptions = proxy.$TOOL.dictTypeList('GENDER').map((item) => {
		return {
			value: item['dictValue'],
			label: item['name']
		}
	})
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				userCenterApi.userUpdateUserInfo(formData.value).then(() => {
					submitLoading.value = false
					// 更新前端缓存
					// proxy.$store.commit('SET_userInfo', formData.value)
					// proxy.$TOOL.data.set('USER_INFO', formData.value)
					nextTick(() => {
						loginApi.getLoginUser().then((loginUser) => {
							tool.data.set('USER_INFO', loginUser)
							userInfo.value = loginUser
						})
					})
					message.success('更新成功')
					// 获取用户的菜单
					userCenterApi.userLoginMenu().then(menu=>{
						tool.data.set('MENU', menu)
						location.reload()
					})
				})
			})
			.catch(() => {
				submitLoading.value = false
			})
	}
	const layout = {
		labelCol: {
			span: 4
		},
		wrapperCol: {
			span: 12
		}
	}
	// 显示短信验证码弹框
	const showPhoneValidation = () => {
		formRef.value.validate().then(() => {
			if (formData.value.phone === null || formData.value.phone.trim() === '') return
			phoneValidationFormData.value.phone = formData.value.phone
			phoneValidationFormData.value.validCode = null
			// 显示弹框
			phoneValidationVisible.value = true
		})
	}
	// 显示邮箱验证码弹框
	const showEmailValidation = () => {
		formRef.value.validate().then(() => {
			if (formData.value.email === null || formData.value.email.trim() === '') return
			emailValidationFormData.value.email = formData.value.email
			emailValidationFormData.value.validCode = null
			// 显示弹框
			emailValidationVisible.value = true
		})
	}
	const showPhoneMachineVerification = () => {
		phoneMachineValidationVisible.value = true
		// 获取内部图片验证码（这里是获取一个令牌）
		loginApi.getPicCaptcha().then((data) => {
			phoneMachineValidCodeBase64.value = data.validCodeBase64 // 图片验证码
			phoneMachineValidationFormData.value.validCodeReqNo = data.validCodeReqNo // 请求令牌
		})
	}
	const showEmailMachineVerification = () => {
		emailMachineValidationVisible.value = true
		// 获取内部图片验证码（这里是获取一个令牌）
		loginApi.getPicCaptcha().then((data) => {
			emailMachineValidCodeBase64.value = data.validCodeBase64 // 图片验证码
			emailMachineValidationFormData.value.validCodeReqNo = data.validCodeReqNo // 请求令牌
		})
	}
	// 发送短信验证码
	const sendPhoneVerifyCode = () => {
		phoneMachineValidationFormData.value.phone = formData.value.phone
		// 获取到里面的验证码，并发送短信
		// 禁用发送按钮，并设置为倒计时
		phoneState.value.smsSendBtn = true
		const phoneInterval = window.setInterval(() => {
			if (phoneState.value.time-- <= 0) {
				phoneState.value.time = 300
				phoneState.value.smsSendBtn = false
				window.clearInterval(phoneInterval)
			}
		}, 1000)
		loginApi
			.getPhoneValidCode(phoneMachineValidationFormData.value)
			.then((data) => {
				const hide = message.loading('验证码发送中..', 0)
				setTimeout(hide, 500)
				phoneMachineValidationFormData.value.validCode = ''
				phoneMachineValidationVisible.value = false
				phoneValidationFormData.value.validCodeReqNo = data
			})
			.catch(() => {
				// setTimeout(hide, 100)
				clearInterval(phoneInterval)
				phoneState.value.smsSendBtn = false
			})
	}
	// 发送邮箱验证码
	const sendEmailVerifyCode = () => {
		emailMachineValidationFormData.value.email = formData.value.email
		// 获取到里面的验证码，并发送短信
		// 禁用发送按钮，并设置为倒计时
		emailState.value.emailSendBtn = true
		const emailInterval = window.setInterval(() => {
			if (emailState.value.time-- <= 0) {
				emailState.value.time = 300
				emailState.value.emailSendBtn = false
				window.clearInterval(emailInterval)
			}
		}, 1000)
		loginApi
			.getEmailValidCode(emailMachineValidationFormData.value)
			.then((data) => {
				const hide = message.loading('验证码发送中..', 0)
				setTimeout(hide, 500)
				emailMachineValidationFormData.value.validCode = ''
				emailMachineValidationVisible.value = false
				emailValidationFormData.value.validCodeReqNo = data
			})
			.catch(() => {
				// setTimeout(hide, 100)
				clearInterval(emailInterval)
				emailState.value.smsSendBtn = false
			})
	}
	const cancelPhoneValidation = () => {
		phoneValidationFormData.value = {}
	}
	const cancelEmailValidation = () => {
		emailValidationFormData.value = {}
	}
	const validatePhone = () => {
		if (!phoneValidationFormData.value.validCodeReqNo) {
			message.info("请获取验证码")
			return
		}
		phoneValidationFormRef.value.validate().then(() => {
			loginApi.phoneVerification(phoneValidationFormData.value).then(res => {
				message.success("手机号验证成功")
				phoneValidationVisible.value = false
				loginApi.getLoginUser().then((loginUser) => {
					proxy.$TOOL.data.set('USER_INFO', loginUser)
					userInfo.value = loginUser
					formData.value = loginUser
					userCenterApi.userLoginMenu().then(res => {
						proxy.$TOOL.data.set('MENU', res)
						location.reload()
					})
				})
			}).catch(err => {
				console.log(err)
			})
		})
	}
	const validateEmail = () => {
		if (!emailValidationFormData.value.validCodeReqNo) {
			message.info("请获取验证码")
			return
		}
		emailValidationFormRef.value.validate().then(() => {
			loginApi.emailVerification(emailValidationFormData.value).then(res => {
				message.success("邮箱验证成功")
				emailValidationVisible.value = false
				loginApi.getLoginUser().then((loginUser) => {
					proxy.$TOOL.data.set('USER_INFO', loginUser)
					userInfo.value = loginUser
					formData.value = loginUser
					userCenterApi.userLoginMenu().then(res => {
						proxy.$TOOL.data.set('MENU', res)
						location.reload()
					})
				})
			}).catch(err => {
				console.log(err)
			})
		})
	}
</script>

<style scoped></style>
